package com.xsq.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.xsq.BaseActivity;
import com.xsq.Constant;
import com.xsq.KeyBoardListener;
import com.xsq.PosMainActivity;
import com.xsq.R;
import com.xsq.URLConstant;
import com.xsq.util.HttpInterface;
import com.xsq.util.ServerUtils;

/**
 * 消费管理:消费查询，周统计，月统计,消费纠错,回退上一笔
 * @author Administrator
 *
 */
@SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak" })
public class ConsumeMngActivity extends BaseActivity {

	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.consume_main);
		
		
	
		
		preferences = getSharedPreferences(Constant.CACHE_XSQ_POS, MODE_PRIVATE);
		editor = preferences.edit();
		
		serverUtils = new ServerUtils(preferences, editor);
		hi = new HttpInterface(serverUtils);
		
		myWebView = (WebView) findViewById(R.id.webview);

		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false); // 支持缩放
		webSettings.setBuiltInZoomControls(false); // 显示放大缩小

		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 解决缓存问题
		myWebView.addJavascriptInterface(new DeviceOp(this), "appControl");
		myWebView.setWebViewClient(new MyWebViewClient());
		myWebView.setWebChromeClient(new MyWebChromeClient());
		myWebView.loadUrl(URLConstant.PAGE_CONSUME_MONG);
		
		KeyBoardListener.getInstance(this).init();
	}

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b2 = new AlertDialog.Builder(ConsumeMngActivity.this).setTitle("提示：").setMessage(message)
					.setPositiveButton("ok", new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}
	}

	private class MyWebViewClient extends WebViewClient {
		/**
		 * 如果希望点击链接由自己处理，而不是新开Android的系统browser中响应该链接。
		 * 给WebView添加一个事件监听对象（WebViewClient)并重写其中的一些方法：
		 * shouldOverrideUrlLoading：对网页中超链接按钮的响应。当按下某个连接时
		 * WebViewClient会调用这个方法，并传递参数：按下的url。比如当webview内嵌
		 * 网页的某个数字被点击时，它会自动认为这是一个电话请求，会传递url：tel:123,
		 * 如果你不希望如此可通过重写shouldOverrideUrlLoading函数解决
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 当开启新的页面的时候用webview来进行处理而不是用系统自带的浏览器处理
			// 互联网用：webView.loadUrl("http://www.google.com");
			// 本地文件用：webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放
			view.loadUrl(url);
			return true;
		}

		/**
		 * 载入页面完成的事件
		 **/
		@Override
		public void onPageFinished(WebView view, String url) {
			// 获取网页内容
			// view.loadUrl("javascript:window.local_obj.showSource"+
			// "('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			super.onPageFinished(view, url);
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。

			Toast.makeText(getApplicationContext(), "加载失败,请联系管理员", Toast.LENGTH_LONG).show();
		}
	}

	
	private static final int GO_HOME = 1000;
	private static final int GO_CONSUME_SRCH = 1001;//消费查询
	private static final int GO_CONSUME_JC = 1002;//纠错
	private static final int GO_CONSUME_JCLOG = 1003;//纠错查询
	private static final int GO_CONSUME_PRINT = 1004;//打印
	private static final int GO_CONSUME_BACK = 1005;//回退
	
	
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GO_HOME:
				loadHome();
				break;
			case GO_CONSUME_SRCH:
				loadConsumeSrchPage();
				break;
			case GO_CONSUME_JC:
				loadConsumeJcPage();
				break;
			case GO_CONSUME_JCLOG:
				loadConsumeJcLogPage();
				break;
			case GO_CONSUME_PRINT:
				loadConsumePrintPage();
				break;
			case GO_CONSUME_BACK:
				loadConsumeBackPage();
				break;
				
			}
		}
	};
	
	private void loadHome() {
		Intent intent = new Intent(this, PosMainActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	private void loadConsumeSrchPage() {
		Intent intent = new Intent(this, ConsumeSrchActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadConsumeJcPage() {

		Intent intent = new Intent(this, ConsumeJcActivity.class);
		intent.putExtra("fromPage", Constant.PAGE_FLAG_MAIN_CONSUME_MNG);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadConsumeJcLogPage() {
		Intent intent = new Intent(this, ConsumeJcLogActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	private void loadConsumePrintPage() {

		Intent intent = new Intent(this, ConsumePrintActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	
	private void loadConsumeBackPage() {

		Intent intent = new Intent(this, ConsumeBackActivity.class);
		intent.putExtra("fromPage", Constant.PAGE_FLAG_MAIN_CONSUME_MNG	);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
         if(keyCode == KeyEvent.KEYCODE_BACK){
        	 loadHome();
             return true;
         }
         return super.onKeyDown(keyCode, event);
     }
	
	private class DeviceOp {

		private Context mContext;

		public DeviceOp(Context c) {
			mContext = c;
		}

		@JavascriptInterface
		public String doTest() {
			Toast.makeText(mContext, "test ... test", Toast.LENGTH_SHORT).show();
			return "1";
		}
		
		
		@JavascriptInterface
		public String toHome() {

			try{
				mHandler.sendEmptyMessage(GO_HOME);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public String toSrchPage() {

			try{
				mHandler.sendEmptyMessage(GO_CONSUME_SRCH);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String toJcPage() {

			try{
				mHandler.sendEmptyMessage(GO_CONSUME_JC);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String toJcLogPage() {

			try{
				mHandler.sendEmptyMessage(GO_CONSUME_JCLOG);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public String toConsumePrintPage() {

			try{
				mHandler.sendEmptyMessage(GO_CONSUME_PRINT);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		/**
		 * 跳转到交易回退页面
		 * @return
		 */
		@JavascriptInterface
		public String toConsumeBackPage() {

			try{
				mHandler.sendEmptyMessage(GO_CONSUME_BACK);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		
		@JavascriptInterface
		public String validateOperPwd(String pwd){
			try{
				if(pwd.equals(getOperAdmin())){
					return "1";
				}
				return "0";
			}catch(Exception e){
				return "-1";
			}
		}
		
		
		@JavascriptInterface
		public String doUpdatePwd(String oldpwd,String newpwd) {

			try{
				if (oldpwd==null || newpwd==null) {
					//必选参数为空
					return "-1";
				} else {
					
					//格式验证
				
					if(!getOperAdmin().equals(oldpwd)){
						return "旧密码不对";
					}else{
						//修改新密码
						editor.putString(Constant.CACHE_PWD_USER, newpwd);
						editor.commit();
						
						return "1";
					}
				
				}
			}catch(Exception e){
				return "-1";
			}
		}
		
		/**
		 * 查询定额消费设置信息
		 * @return
		 */
		@JavascriptInterface
		public String queryConsumeQuato() {

			try{
				String deMoney = "0";
				String sf = getSFQuatoConsume();
				if(sf.equals("1")){
					deMoney = getQuatoConsumeMoney();
				}
				
				return sf+","+deMoney;
				
				
			}catch(Exception e){
				return "-1";
			}
		}
		
		
		/**
		 * 保留消费定额相关设置
		 * @param quatoMode
		 * @param quatoMoney
		 * @return
		 */
		@JavascriptInterface
		public String saveQuatoInfo(String quatoMode,String quatoMoney){
			try{
				//System.out.println("-----------"+quatoMode+"----"+quatoMoney);
				
				editor.putString(Constant.CACHE_CONSUME_QUATO, quatoMode);
				editor.putString(Constant.CACHE_CONSUME_QUATO_MONEY, quatoMoney);
				editor.commit();
				
				return "1";
			}catch(Exception e){
				e.printStackTrace();
				return "-100";
			}
		}
	
	}

}
